<template>
  <div>
    <el-upload
      ref="Upload"
      action="/api/cbb-hzz/file/upload"
      :headers="headers"
      :list-type="listType"
      :limit="limit"
      :fileList="fileList"
      :accept="acceptFun"
      :before-upload="beforeUpload"
      :on-preview="handlePreview"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-exceed="handleExceed" 
      :class="{ hide: hideUpload }"
    >
      <div>
        <i class="el-icon-plus" v-if="listType === 'picture-card'"></i>
        <el-button size="small" type="primary" v-else>点击上传</el-button>
      </div>
    </el-upload>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="viewImageUrl"
      v-show="listType === 'picture-card'"
    />
  </div>
</template>
<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { fileSize } from "@/util/upload";
export default {
  name: "UploadImage",

  components: {
    ElImageViewer
  },
  props: {
    value: {},
    // 类型
    listType: {
      type: String,
      default: "picture-card"
    },
    // 最大允许上传个数
    limit: {
      type: Number
    },
    // 接受上传的文件类型
    accept: {
      type: String
    },
    // 文件大小限制，单位KB，默认5MB
    maxSize: {
      type: Number,
      default: 5 * 1024
    }
  },
  data() {
    return {
      tempUrl: "",
      hideUpload: false,
      fileList: [],
      showViewer: false,
      viewImageUrl: [],
      headers: {
        Authorization: "Bearer "
      }
    };
  },
  mounted() {
    this.fileFormat([], "default");
    this.watchValue();
  },
  computed: {
    acceptFun() {
      switch (this.accept) {
        case "picture":
          return ".png, .jpg, .jpeg";
        case "video":
          return ".mp4";
        case "audio":
          return ".mp3";
        case "file":
          return ".pdf,.txt,.word,.docx,.doc,.xlsx,.zip,.md";
        default:
          return "*";
      }
    }
  },
  watch: {
    value() {
      this.watchValue();
    }
  },
  methods: {
    watchValue() {
      this.updateFile();
    },
    beforeUpload(file) {
      const fileMax = file.size / 1024 < this.maxSize;
      if (!fileMax) {
        this.$message.error(
          `上传图片大小不能超过 ${fileSize(this.maxSize / 1024)}!`
        );
      }
      return !!fileMax;
    },
    handleSuccess(res, file, fileList) {
      this.fileFormat(fileList, "add");
    },
    handleRemove(file, fileList) {
      this.fileFormat(fileList, "remove");
    },
    fileFormat(fileList, type) {
      if (type === "default") {
        const arr = this.value
          ? this.value.constructor === Array
            ? this.value
            : this.value.split(",")
          : [];
        if (arr.length > 0) {
          this.fileList = arr.map(item => {
            return {
              id: item.id || item,
              name: item.name || "",
              url: `/api/${this.$apiUrl}-hzz/file/not-auth/download/${item.id || item}`
            };
          });
        } else {
          this.fileList = [];
        }
      } else if (type === "add") {
        this.fileList = fileList.map(item => {
          if (item.response) {
            return {
              id: item.response.data,
              name: item.name,
              url: `/api/${this.$apiUrl}-hzz/file/not-auth/download/${item.response.data}`
            };
          } 
            return item;
          
        });
        const str = this.fileList.map(item => {
          return item.id;
        });
        this.$emit("input", str.toString());
      } else if (type === "remove") {
        this.fileList = fileList;
        const str = fileList.map(item => {
          const index = item.url.indexOf("download/");
          let obj;
          if (index !== -1) {
            obj = item.url.lastIndexOf("download/");
          }
          const url =
            index !== -1
              ? item.url.substring(obj + 9, item.url.length)
              : item.response.id;
          return url;
        });
        this.$emit("input", str.toString());
      }
      this.updateFile();
    },
    handleExceed() {
      this.$message.error(`最多上传${this.limit}`);
    },
    updateFile() {
      if (this.fileList.length >= this.limit) {
        this.hideUpload = true;
      } else {
        this.hideUpload = false;
      }
    },
    handlePreview(file) {
      this.viewImageUrl = [file.url];
      this.showViewer = true;
    },
    closeViewer() {
      this.showViewer = false;
    }
  }
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none !important;
}

.hide .el-upload--text {
  display: none !important;
}

.el-upload-list__item-thumbnail {
  object-fit: contain;
}

.el-upload-list__item-name {
  display: inline;
}

.el-upload-list__item.is-success .el-upload-list__item-status-label {
  display: inline;
  float: right;
}
</style>
